import axios from 'axios'
import Vue from 'vue'
import router from '../router'
import { getToken, removeToken } from '../utils/auth'
const http = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || '/admin/api'
  // baseURL: "http://localhost:6000/admin/api"
})

http.interceptors.request.use(config => {
  if (getToken()) {
    config.headers.Authorization = 'Bearer ' + getToken()
  }
  return config
})

http.interceptors.response.use(config => {
  return config.data
}, error => {
  // 403数据库校验错误
  switch (error.response.status) {
    case 401:
      let msg = ''
      error.response.data.forEach(m => {
        msg += `字段:${m.parameter}   ${m.errorMsg}`
      })
      Vue.prototype.$notify.error({
        title: '数据格式错误',
        message: msg
      })
      break;
    case 403:
      Vue.prototype.$notify.error({
        title: '错误',
        message: error.response.data
      })
      removeToken()
      router.push('/login')
      break
  }
})

export default http